<?php  

if(!class_exists('Easy_SEO')) :

class Easy_SEO {

	public function __construct( $args ) {

		$this->configs = wp_parse_args( $args, array(
			'easy_seo' => true,
			'front_page_desc' => '',
			'front_page_keywords' => '',
			'post_desc'	=> true,
			'post_keywords' => true,
		) );
		add_action( 'wp_head', array($this, 'render_meta') );
		if ( version_compare( $GLOBALS['wp_version'], '4.1', '<' ) ) {
			add_filter( 'wp_title', array($this, 'render_wp_title'), 10, 2 );
			add_action( 'wp_head', array($this, 'render_title') );
		}
	}

	/**
	 * Title shim for sites older than WordPress 4.1.
	 *
	 * @link https://make.wordpress.org/core/2014/10/29/title-tags-in-4-1/
	 * @todo Remove this function when WordPress 4.3 is released.
	 */
	function render_title() {
	?>
		<title><?php wp_title( '|', true, 'right' ); ?></title>
	<?php
	}

	/**
	 * Filters wp_title to print a neat <title> tag based on what is being viewed.
	 *
	 * @param string $title Default title text for current view.
	 * @param string $sep Optional separator.
	 * @return string The filtered title.
	 */
	function render_wp_title( $title, $sep = ' | ' ) {

		if ( is_feed() ) {
			return $title;
		}

		global $page, $paged, $post;
		$title = '';
		if(is_singular()) {
			$title .= $post->post_title . ' - ';
		}
		// Add the blog name
		$title .= get_bloginfo( 'name', 'display' );

		// Add the blog description for the home/front page.
		$site_description = get_bloginfo( 'description', 'display' );
		if ( $site_description && ( is_home() || is_front_page() ) ) {
			$title .= " $sep $site_description";
		}

		// Add a page number if necessary:
		if ( ( $paged >= 2 || $page >= 2 ) && ! is_404() ) {
			$title .= " $sep " . sprintf( __( 'Page %s', 'everbox' ), max( $paged, $page ) );
		}

		return $title;
	}

	function render_meta() {

		global $page;

		$keywords = $description = '';
		$easy_seo = $this->configs['easy_seo'];

		if( $easy_seo && !function_exists('wpseo_auto_load') ) {
			if(is_front_page()) {
				$description = $this->configs['front_page_desc'];
				$keywords = $this->configs['front_page_keywords'];
			} elseif (is_single()) {
				global $post;
				if( $this->configs['post_desc'] ) {
					if($post->post_excerpt) {
						$description = $post->post_excerpt;
					} else {
						$description = wp_trim_words( $post->post_content, 40 );
					}
				}
				if( $this->configs['post_keywords'] ) {
					$tags = wp_get_post_tags( $post->ID );
					foreach ($tags as $tag) {
						$keywords .= $tag->name . ', ';
					}
				}
			}
			if( $keywords != '' ) {
				printf('<meta name="keywords" content="%s" />', esc_attr( $keywords ));
			}
			if( $description != '' ) {
				printf('<meta name="description" content="%s" />', esc_attr( $description ));
			}
		}
	}	
}

endif;

?>